<template>
  <div class="orders-container">
    <div class="page-header">
      <div class="header-content">
        <el-button 
          type="primary" 
          size="small" 
          @click="$router.push('/')"
          class="back-button"
        >
          返回首页
        </el-button>
        <h1>我的订单</h1>
      </div>
    </div>
    
    <div class="order-tabs">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待付款" name="10"></el-tab-pane>
        <el-tab-pane label="待发货" name="20"></el-tab-pane>
        <el-tab-pane label="待收货" name="30"></el-tab-pane>
        <el-tab-pane label="已完成" name="40"></el-tab-pane>
        <el-tab-pane label="已取消" name="0"></el-tab-pane>
      </el-tabs>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton v-for="i in 3" :key="i" style="margin-bottom: 20px" :rows="4" animated />
    </div>
    
    <div v-else-if="orders.length === 0" class="empty-orders">
      <el-empty description="暂无订单数据">
        <el-button type="primary" @click="$router.push('/')">去购物</el-button>
      </el-empty>
    </div>
    
    <div v-else class="orders-list">
      <div class="order-card" v-for="order in orders" :key="order.id">
        <div class="order-header">
          <div class="order-info">
            <span class="order-number">订单号: {{ order.orderNo }}</span>
            <span class="order-date">下单时间: {{ formatDate(order.createdAt) }}</span>
          </div>
          <div class="order-status" :class="getStatusClass(order.status)">
            {{ getStatusText(order.status) }}
          </div>
        </div>
        
        <div class="order-items">
          <div class="order-item" v-for="item in (order.items || [])" :key="item.productId">
            <div class="item-image">
              <img :src="item.mainImageUrl || '@/assets/homelogo.png'" :alt="item.name">
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.name }}</div>
              <div class="item-price">¥{{ item.unitPrice.toFixed(2) }}</div>
              <div class="item-quantity">x{{ item.quantity }}</div>
            </div>
          </div>
        </div>
        
        <div class="order-footer">
          <div class="order-total">
            <span>共{{ getTotalQuantity(order.items || []) }}件商品</span>
            <span class="total-price">合计: ¥{{ order.totalAmount.toFixed(2) }}</span>
          </div>
          <div class="order-actions">
            <el-button size="small" type="primary" v-if="order.status === 10" @click="goToPayment(order.orderNo)">去付款</el-button>
            <el-button size="small" type="success" v-if="order.status === 30" @click="confirmReceipt(order.orderNo)">确认收货</el-button>
            <el-button size="small" v-if="order.status === 40" @click="repurchase(order)">再次购买</el-button>
            <el-button size="small" type="danger" v-if="order.status === 10" @click="cancelOrder(order.orderNo)">取消订单</el-button>
            <el-button size="small" @click="viewOrderDetail(order.orderNo)">查看详情</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div v-if="orders.length > 0" class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="totalOrders"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

interface OrderItem {
  productId: number
  name: string
  mainImageUrl: string
  unitPrice: number
  quantity: number
}

interface Order {
  id: number
  orderNo: string
  status: number
  totalAmount: number
  createdAt: string
  items: OrderItem[]
}

const router = useRouter()
const activeTab = ref('all')
const loading = ref(true)
const orders = ref<Order[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalOrders = ref(0)

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取订单状态文本
const getStatusText = (status: number) => {
  const statusMap: {[key: number]: string} = {
    0: '已取消',
    10: '待付款',
    20: '待发货',
    30: '待收货',
    40: '已完成'
  }
  return statusMap[status] || '未知状态'
}

// 获取订单状态样式类
const getStatusClass = (status: number) => {
  const classMap: {[key: number]: string} = {
    0: 'status-cancelled',
    10: 'status-pending-payment',
    20: 'status-pending-shipment',
    30: 'status-pending-receipt',
    40: 'status-completed'
  }
  return classMap[status] || 'status-unknown'
}

// 计算订单商品总数量
const getTotalQuantity = (items: OrderItem[]) => {
  return items ? items.reduce((total, item) => total + item.quantity, 0) : 0
}

// 标签页切换
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
  currentPage.value = 1
  fetchOrders()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchOrders()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchOrders()
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    const params: any = {
      current: currentPage.value,
      size: pageSize.value
    }
    
    // 只有在非"all"状态时才添加status参数
    if (activeTab.value !== 'all') {
      params.status = parseInt(activeTab.value)
    }
    
    const response = await axios.get('/api/user/orders', { params })
    
    orders.value = response.data.records || []
    totalOrders.value = response.data.total || 0
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败，请稍后重试')
    orders.value = []
    totalOrders.value = 0
  } finally {
    loading.value = false
  }
}

// 去支付
const goToPayment = (orderNo: string) => {
  router.push(`/payment/${orderNo}`)
}

// 确认收货
const confirmReceipt = async (orderNo: string) => {
  try {
    await ElMessageBox.confirm('确认已收到商品吗？', '确认收货', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await axios.post(`/api/user/orders/${orderNo}/confirm-receipt`)
    ElMessage.success('确认收货成功')
    fetchOrders() // 刷新订单列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败，请稍后重试')
    }
  }
}

// 取消订单
const cancelOrder = async (orderNo: string) => {
  try {
    await ElMessageBox.confirm('确认取消订单吗？', '取消订单', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里需要后端提供取消订单的接口
    // await axios.post(`/api/user/orders/${orderNo}/cancel`)
    ElMessage.info('取消订单功能暂未开放')
    // fetchOrders() // 刷新订单列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败，请稍后重试')
    }
  }
}

// 再次购买
const repurchase = (order: Order) => {
  // 这里可以将订单商品重新加入购物车
  ElMessage.info('再次购买功能开发中')
}

// 查看订单详情
const viewOrderDetail = (orderNo: string) => {
  router.push(`/order/${orderNo}`)
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-button {
  flex-shrink: 0;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
  flex: 1;
}

.order-tabs {
  margin-bottom: 20px;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.order-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.order-status {
  font-weight: bold;
  font-size: 14px;
}

.status-pending-payment { color: #e6a23c; } /* 待付款 */
.status-pending-shipment { color: #409eff; } /* 待发货 */
.status-pending-receipt { color: #67c23a; } /* 待收货 */
.status-completed { color: #909399; } /* 已完成 */
.status-cancelled { color: #f56c6c; } /* 已取消 */
.status-unknown { color: #999; } /* 未知状态 */

.order-items {
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.order-item {
  display: flex;
  gap: 15px;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.item-price {
  font-size: 14px;
  color: #f56c6c;
}

.item-quantity {
  font-size: 14px;
  color: #999;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}

.order-total {
  font-size: 14px;
  color: #666;
}

.total-price {
  margin-left: 10px;
  font-weight: bold;
  color: #f56c6c;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.loading-container {
  padding: 20px;
}

.empty-orders {
  text-align: center;
  padding: 50px 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px 0;
}
</style>